/**
 *			\author ITII - ISEN - P6
 *			\author Jonathan CASSAING
 *			\file MailArchiver.cpp
 *			\version 0.2
 *			\date 09/09/2010
 */


#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <sstream>
#include "SmtpProtocol.h"
#include "MailArchiver.h"


using namespace std;


string MailArchiver::_folderPath = "./archive";


string MailArchiver::getFolderPath()
{
	return _folderPath;
}

void MailArchiver::setFolderPath(string folderPath)
{
	_folderPath = folderPath;
}

int MailArchiver::saveMail(const Mail & mail)
{
	string	cmd("mkdir ");

	cmd += _folderPath;
	system(cmd.c_str());

	cmd += "/" + mail.getMailFrom();
	system(cmd.c_str());

	FILE *		fd		= NULL;
	bool		open		= false;
	string		filePath	= _folderPath + "/" + mail.getMailFrom();
	string		mailFormated;
	ostringstream	hour;
	ostringstream	min;
	ostringstream	sec;
	struct tm *	time_struct;		//Structure Heures:Minutes:Secondes
	time_t		timesec;		//Temps depuis le 1er Janvier 1970 en secondes

	time(&timesec);
	time_struct=localtime(&timesec);

	hour	<< time_struct->tm_hour;
	min	<< time_struct->tm_min;
	sec	<< time_struct->tm_sec;

	filePath += (string)"/mail-" +
		    hour.str() + "h" +
		    min.str() + "min" +
		    sec.str() + "s.txt";

	fd = fopen( filePath.c_str(), "w" );
	if( NULL == fd )
		return -1;
	else open = true;

	mailFormated = SmtpProtocol::formatMail(mail);

	fwrite( mailFormated.c_str(), strlen(mailFormated.c_str()), 1, fd );

	if( true == open )
		fclose(fd);

	return 0;
}
